package com.atguigu.state;

import com.atguigu.bean.WaterSensor;
import com.atguigu.utils.ITtoListUtil;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.Comparator;
import java.util.List;

public class Flink05_Key_ListState {
    public static void main(String[] args) {
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port",10000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(configuration);
        env.setParallelism(2);

        //需求实现：针对每个传感器输出最高的3个水位值
        env
                .socketTextStream("hadoop162", 9999)
                .map(line -> {
                    String[] data = line.split(",");
                    return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
                })
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                    private ListState<Integer> listState;

                    //重写open方法
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        listState = getRuntimeContext().getListState(new ListStateDescriptor<Integer>("listState", Integer.class));
                    }

                    //对单个数据的处理
                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                        //将数据保存到状态中
                        listState.add(value.getVc());

                        //判断当前状态中的数据有没有四个
                        List<Integer> list = ITtoListUtil.toList(listState.get());
                        if (list.size() >=4){
                            //对当前集合进行排序
                            list.sort(new Comparator<Integer>() {
                                @Override
                                public int compare(Integer o1, Integer o2) {
                                    return o2.compareTo(o1);
                                }
                            });
                            //排完序之后删除最后一个元素
                            list.remove(list.size()-1);
                        }

                        //更新状态
                        listState.update(list);

                        //结果输出
                        out.collect(list.toString());

                    }
                })
                .print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
